package com.maimang.platform.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源
 *
 * @author Rocky
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
	private Map<Object, Object> allResolvedDataSources = new HashMap<>();

	public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
		super.setDefaultTargetDataSource(defaultTargetDataSource);
		super.setTargetDataSources(targetDataSources);
		super.afterPropertiesSet();
	}

	@Override
	protected Object determineCurrentLookupKey() {
		return DynamicDataSourceContextHolder.getDataSourceType();
	}

	/**
	 * 添加数据源
	 *
	 * @param name
	 * @param dataSource
	 */
	public void addDataSource(Object name, DataSource dataSource) {
		if (allResolvedDataSources.containsKey(name))
			allResolvedDataSources.remove(name);
		allResolvedDataSources.put(name, dataSource);
		setTargetDataSources(allResolvedDataSources);
	}

	/**
	 * 删除数据源
	 *
	 * @param name
	 * @return
	 */
	public Object deleteDataSource(Object name) {
		Object rst = null;
		if (allResolvedDataSources.containsKey(name)) {
			rst = allResolvedDataSources.get(name);
			allResolvedDataSources.remove(name);
			setTargetDataSources(allResolvedDataSources);
		}
		return rst;
	}

	/**
	 * 检查数据源是否存在
	 *
	 * @param name
	 * @return
	 */
	public Boolean isExistDataSource(Object name) {
		return allResolvedDataSources.containsKey(name);
	}
}